<?php

/**
* alltosun.com 售后服务 index.php
* ============================================================================
* 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* $Author: 吴松键 (wusj@alltosun.com) $
* $Date: 2015-01-27 上午10:50:12 $
* $Id$
*/

class Action
{
    private $user_id;

    public function __construct()
    {
        checkLogin(get_url());
        $this->user_id = user_helper::get_user_id();
    }

    public function __call($action = '', $param = array())
    {
        $id = (int)$action;
        if (!$id) {
            return array('请选择服务的订单', 'error', AnUrl('refund'));
        }
        /*
        service_helper::auto_refund_status($id); // 自动状态
        */

        $service_info = service_helper::get_refund_info($id, 0);
        if ($this->user_id != $service_info['user_id']) {
            return '您不能操作别人的服务单';
        }

        Response::assign('service_info', $service_info);

        display_template('service_detail.html');
    }

    /**
     * 选择服务类型
     */
    public function slt_service()
    {
        $order_id = Request::getParam('order_id', 0);
        if (!$order_id) {
            return array('请选择需要使用售后服务的订单', 'error', AnUrl('order'));
        }
        $order_info = _uri('order', $order_id);
        if ($order_info['user_id'] != $this->user_id) {
            return array('您不能操作别人的订单', 'error', AnUrl('order'));
        }

        if ($order_info['progress'] != 20) {
            return array('当前订单状态不能售后功能', 'error', AnUrl('order'));
        }

        Response::assign('order_id', $order_id);

        Response::display('m/slt_service.html');
    }

    /**
     * 填写服务单
     */
    public function index()
    {
        $order_id = Request::getParam('order_id', 0);
        $type     = Request::getParam('type', 0);
        $address_id = Request::getParam('address_id', 0);

        if (!$order_id &&  isset($_SESSION['service_tmp']) && $_SESSION['service_tmp']) {
            $order_id     = $_SESSION['service_tmp']['order_id'];
            $type         = $_SESSION['service_tmp']['type'];
            $relation_num = $_SESSION['service_tmp']['relation_num'];
            $reason       = $_SESSION['service_tmp']['reason'];
            $img          = $_SESSION['service_tmp']['img'];

            $img_list = array();
            if (is_array($img)) {
                foreach ($img as $k => $v) {
                    if (!$v) {
                        continue;
                    }
                    $img_list[] = _uri('attachment', $v);
                }
            }

            Response::assign('relation_num', $relation_num);
            Response::assign('reason', $reason);
            Response::assign('img_list', $img_list);
        } else {
            unset($_SESSION['service_tmp']);
        }

        if (!$order_id) {
            return array('请选择需要使用售后服务的订单', 'error', AnUrl('order'));
        }

        $order_info = _uri('order', $order_id);
        if ($order_info['user_id'] != $this->user_id) {
            return array('您不能操作别人的订单', 'error', AnUrl('order'));
        }

        if ($order_info['progress'] != 20) {
            return array('当前订单状态不能售后功能', 'error', AnUrl('order'));
        }
        if ($order_info['express_receiver_time'] == '0000-00-00 00:00:00') {
            express_helper::express_info_by_order($order_id);
        }
        if ($order_info['express_receiver_time'] == '0000-00-00 00:00:00') {
            $order_info['express_receiver_time'] = $order_info['receiver_time'];
        }

        // 收货时间
        $has_day = floor((time() - strtotime($order_info['express_receiver_time']))/(3600*24));
        $order_detail = service_helper::get_relation_info($order_id);
        $has_day = 0;

        // 获取地址列表
        if ($address_id) {
            $address_info = _uri('address', $address_id);
            $order_info['receiver'] = $address_info['receiver'];
            $order_info['mobile'] = $address_info['mobile'];
            $order_info['address'] = $address_info['address'];
            $order_info['province'] = $address_info['province'];
            $order_info['city'] = $address_info['city'];
            $order_info['district'] = $address_info['district'];
            $address_list = array();
            $address_ids  = array();
        } else {
            $address_list = _widget('address')->get_list();
            $address_info = array();
            if ($address_list) {
                foreach ($address_list as $k=>$v) {
                    if ($order_info['province'] == $v['province'] && $order_info['district'] == $v['district'] && $order_info['receiver'] == $v['receiver'] && $order_info['address'] == $v['address'] && $order_info['mobile'] == $v['mobile']) {
                        $address_info = $v;
                        break;
                    }
                }
            }
            $address_ids = provincial_helper::get_id_by_title($order_info['province'], $order_info['city'], $order_info['district']);
        }

        Response::assign('address_ids', $address_ids);
        Response::assign('address_list', $address_list);
        Response::assign('address_info', $address_info);
        Response::assign('has_day', $has_day);
        Response::assign('order_info', $order_info);
        Response::assign('order_detail', $order_detail);
        Response::assign('type', $type);

        display_template('service.html');
    }

    /**
     * 检查当前订单是否满足服务条件
     */
    public function check_service_time()
    {
        $type     = Request::Post('type', 0);
        $order_id = Request::Post('order_id', 0);
        if (!$type) {
            return '请选择需要服务的类型';
        }
        if (!$order_id) {
            return '请选择需要操作的订单';
        }

        $order_info = _uri('order', $order_id);
        if ($order_info['user_id'] != $this->user_id) {
            return array('您不能操作别人的订单', 'error', AnUrl('order'));
        }
        if ($order_info['progress'] != 20) {
            return array('当前订单状态不能售后功能', 'error', AnUrl('order'));
        }
        if ($order_info['express_receiver_time'] == '0000-00-00 00:00:00') {
            express_helper::express_info_by_order($order_id);
        }
        if ($order_info['express_receiver_time'] == '0000-00-00 00:00:00') {
            $order_info['express_receiver_time'] = $order_info['receiver_time'];
        }

        // 收货时间
        /*
        $has_day = floor((time() - strtotime($order_info['express_receiver_time']))/(3600*24));
        if ($has_day > 7 && $type == 1) {
            return '当前订单已过退货期限';
        }
        if ($has_day > 14 && $type == 2) {
            return '当前订单已过换货期限';
        }*/

        return 'ok';
    }

    public function save_tmp_session()
    {
        $order_id     = Request::getParam('order_id', 0);
        $relation_ids = explode(',', Request::getParam('ids', ''));
        $relation_num = explode(',', Request::getParam('num', ''));
        $reason       = Request::getParam('reason', '');
        $img          = explode(',', Request::getParam('img', ''));
        $type         = Request::getParam('type', 0);

        $tmp_num = array();
        if ($relation_ids) {
            foreach ($relation_ids as $k => $v) {
                $tmp_num[$v] = $relation_num[$k];
            }
        }
        $_SESSION['service_tmp'] = array(
                'order_id'     => $order_id,
                'relation_num' => $tmp_num,
                'reason'       => $reason,
                'img'          => $img,
                'type'         => $type
            );

        return 'ok';
    }

    /**
     * 提交服务
     */
    public function save_service()
    {
        $info = Request::getParam('info', array());
        $img  = AnFilter::filter_string(Request::getParam('img', ''));

        if (!$info['order_id']) {
            return '请选择需要退款的订单';
        }
        if (!$info['relation_ids']) {
            return '请选择需要退款的商品';
        }
        foreach ($info as $k=>$v) {
            if (!is_numeric($v)) {
                $info[$k] = trim(AnFilter::filter_string($v));
            }
        }
        $order_info = _uri('order', (int)$info['order_id']);
        if (!$order_info) {
            return '请选择需要退款的订单';
        }
        if ($order_info['user_id'] != $this->user_id) {
            return '您不能操作别人的订单';
        }
        if ($order_info['express_receiver_time'] == '0000-00-00 00:00:00') {
            $order_info['express_receiver_time'] = $order_info['receiver_time'];
        }
        
        $refund_info_query = _model('refund')->read(array('order_id'=>$order_info['id'], 'refund_status <='=>20));
        if ($refund_info_query && $info['service_type'] == 1) {
            return '您已经创建了服务单，不能同时创建多个';
        }
        /*
        $has_day = floor((time() - strtotime($order_info['express_receiver_time']))/(3600*24));
        if ($has_day > 7 && $info['service_type'] == 1) {
            return  '超过七天退款时间';
        } elseif ($has_day > 14 && $info['service_type'] == 2) {
            return  '超过七天换货时间';
        }
        if ($info['service_type'] > 3 || $info['service_type'] == 2) {
            return '请选择需要服务的类型';
        }*/

        $refund_info = array(
                'user_id'    => $this->user_id,
                'order_id'   => $order_info['id'],
                'receiver'   => $info['receiver'],
                'mobile'     => $info['mobile'],
                'province'   => $info['province'],
                'city'       => $info['city'],
                'district'   => $info['district'],
                'address'    => $info['address'],
                'type'       => $info['service_type'],
                'note'       => $info['reason'],
                'pay_type'   => $order_info['pay_type']
            );

        $relation_ids = explode(',', $info['relation_ids']);
        $relation_num = explode(',', $info['relation_num']);
        $refund_price = 0;
        if ($info['service_type'] == 1) {
            // 同一时间只能存在一个退款订单
            $has_refund_info = _model('refund')->read(array('order_id'=>$order_info['id'], 'type'=>1, '`refund_status` <'=>20));
            if ($has_refund_info) {
                return '同一时间只能存在一个退款订单';
            }

            $refund_price = 0;
            foreach ($relation_ids as $k=>$v) {
                $relation_info = _uri('order_relation', $v);
                if ($relation_info['order_id'] == $order_info['id']) {
                    $refund_price += $relation_info['goods_price'] * $relation_num[$k];
                }
            }

            // 获取当前订单退款记录
            $refund_list = _model('refund')->getList(array('order_id'=>$order_info['id'], 'type'=>1, 'refund_status <'=>25, 'status'=>1));
            $has_coupon = 0;
            $has_promotion = 0;
            $refund_price_ed = 0;
            if ($refund_list) {
                foreach ($refund_list as $key => $value) {
                    if ($value['is_coupon'] == 1) {
                        $has_coupon = 1;
                    }
                    if ($value['is_promotion'] == 1) {
                        $has_promotion = 1;
                    }
                    $refund_price_ed += $value['refund_price'];
                }
            }

            $refund_info['is_promotion'] = 0;
            $refund_info['is_coupon'] = 0;
            // 订单剩余价格
            $order_surplus_price = $order_info['price'] - $refund_price_ed - $refund_price + $order_info['coupon_offer_price'];
            // 优先扣除满减优惠价格
            if ($has_promotion == 0 && ($refund_price >= $order_info['promotion_offer_price'] || $order_surplus_price < $order_info['promotion_limit_price'])) {
                $refund_price -= $order_info['promotion_offer_price'];
                $refund_info['is_promotion'] = 1;
            }
            if ($refund_price < 0) {
                return '您当前选中的商品价格不够扣除购买商品时所享受的优惠价格，不能退款';
            }

            // 再扣除优惠券价格
            if ($has_coupon == 0 && $order_info['coupon_offer_price']) {
                $order_relation_list = _model('order_relation')->getList(array('order_id'=>$order_info['id']));
                $surplue_coupon_price = 0;
                $new_ids = array_flip($relation_ids);
                foreach ($order_relation_list as $k => $v) {
                    if ($tmp_key = $new_ids[$v['id']] && $v['is_coupon'] == 1) {
                        $surplue_coupon_price += ($v['goods_num']-$relation_num[$tmp_key])*$v['goods_price'];
                    } else {
                        $surplue_coupon_price += $v['goods_num']*$v['goods_price'];
                    }
                }

                if ($refund_price >= $order_info['coupon_offer_price'] || 
                    $surplue_coupon_price < $order_info['coupon_limit_price']) {

                    $refund_price -= $order_info['coupon_offer_price'];
                    $refund_info['is_coupon'] = 1;
                }
                if ($refund_price < 0) {
                    return '您当前选中的商品价格不够扣除购买商品时所使用的优惠价格，不能退款';
                }
            }

            $refund_info['refund_price'] = $refund_price;
            $refund_info['real_price'] = $refund_price;
        } else if ($info['service_type'] == 3) {
            $refund_info['refund_status'] = 20;

            // 发送服务邮件
        }

        // 创建退款订单
        $refund_id = _model('refund')->create($refund_info);

        // 建立图片关系
        $img = explode(',', $img);
        if ($img) {
            foreach ($img as $k=>$v) {
                $v = (int)$v;
                if (!$v || 0 == $v) {
                    continue;
                }
                $img_relaiton = array(
                    'res_name'      => 'service',
                    'res_id'        => $refund_id,
                    'attachment_id' => $v
                );

                _model('attachment_relation')->create($img_relaiton);
            }
        }

        // 建立退款关系表
        foreach ($relation_ids as $k => $v) {
            $order_relation_info  = _uri('order_relation', $v);
            $refund_relation_info = array(
                    'refund_id'         => $refund_id,
                    'order_id'          => $order_info['id'],
                    'order_relation_id' => $v,
                    'refund_num'        => $relation_num[$k],
                    'sku_snapshot_id'   => $order_relation_info['sku_snapshot_id'],
                    'refund_price'      => $order_relation_info['goods_price']
                );
            _model('refund_relation')->create($refund_relation_info);
        }

        // 发送服务邮件
        if ($info['service_type'] == 3) {
            $relation_ids    = explode(',', $info['relation_ids']);
            $sku_snapshot_id = _uri('order_relation', $relation_ids, 'sku_snapshot_id');
            $goods_title     = _uri('sku_snapshot', $sku_snapshot_id, 'goods_title');
            if ($order_info['express_receiver_time']) {
                $time = $order_info['express_receiver_time'];
            } else {
                $time = date("Y-m-d H:i:s", strtotime($order_info['add_time'])+10*24*3600);
            }
            $content = '<p>产品名称：'.$goods_title.'</p>';
            $content .= '<p>购买时间：'.$time.'</p>';
            $content .= '<p>姓名：'.$info['receiver'].'</p>';
            $content .= '<p>手机：'.$info['mobile'].'</p>';
            $content .= '<p>地址：'.$info['province'].' '.$info['city'].' '.$info['district'].' '.$info['address'].'</p>';
            
            mail_helper::mail(Config::get('repair_email'), '联想NBD维修单, NEWBD单号：'.order_helper::order_id_encode($refund_id, 2), $content, 'HTML');
        }

        if (Request::isAjax()) {
            return array(
                'info' => 'ok',
                'id'   => $refund_id
            );
        }

        Response::redirect(AnUrl('service/'.$refund_id));
    }

    /**
     * 取消服务单
     */
    public function cancel_service()
    {
        $id = Request::getParam('id', 0);
        if (!$id) {
            return '请选择需要取消的服务单';
        }

        $service_info = _uri('refund', $id);
        if ($this->user_id != $service_info['user_id']) {
            return '您不能操作别人的服务单';
        }

        if ($service_info['refund_status'] > 5 ) {
            return '当前订单不能取消';
        }

        _model('refund')->update(array('id'=>$id), array('refund_status'=>25));

        return 'ok';
    }

    /**
     * 确认服务单
     */
    public function sure_service()
    {
        $id = Request::getParam('id', 0);
        if (!$id) {
            return '请选择需要操作的服务单';
        }

        $service_info = _uri('refund', $id);
        if ($this->user_id != $service_info['user_id']) {
            return '您不能操作别人的服务单';
        }

        if ($service_info['refund_status'] < 5 ) {
            return '当前订单不能直接确认';
        }

        _model('refund')->update(array('id'=>$id), array('refund_status'=>20));

        return 'ok';
    }
}
?>